#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    QPixmap pixmap;
    ui->setupUi(this);
    pixmap.load(QString("./source/gray.png"));
    ui->label_status_led->setPixmap(pixmap);
    setWindowState(Qt::WindowMaximized);
    this->setWindowTitle(QString("精诚定时器检测台板-"+appVersion+"-"));
    //更新120个设备按键的显示内容
    SetDeviceButtonText();
    //初始化软件信息，配置为上一次使用的文件
    QFile file("./app.json");
    if (file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        QByteArray FileData = file.readAll();
        QString jsonStr;
        jsonStr.append( FileData);
        QJsonDocument JsonDat = QJsonDocument::fromJson(jsonStr.toUtf8());
        ui->lineEdit_fileconfig->setText(JsonDat.object().value("configFileName").toString());
        ui->textEdit->append("APP Version:"+JsonDat.object().value("version").toString());
        ui->comboBox_com->setCurrentIndex(JsonDat.object().value("COM").toInt());
        TestErrorNum = JsonDat.object().value("TestErrorNum").toInt();
        TestAllTimeErrorNum =JsonDat.object().value("TestAllTimeErrorNum").toInt();
        TestOkNum = JsonDat.object().value("TestOkNum").toInt();
        ui->lcdNumber_errorNum->display(TestErrorNum);
        ui->lcdNumber_okNum->display(TestOkNum);
        OpenConfigFile(JsonDat.object().value("configFileName").toString());

        OpenCom();
    }
    else
    {
        QMessageBox::information(this,"错误信息","读取配置文件失败，请手动添加定时器配置文件!");
    }
    ///////////////////////////////////////
    timer_100ms.setInterval(100);
    QObject::connect(&timer_100ms,SIGNAL(timeout()),this,SLOT(Timer_100ms_Slot()));
    timer_100ms.start();
    ////////////////////////////////////
    DeviceRunStatus = 0;//停止检测
    DeviceTestStep = 1;//默认第一步
    NowStepTestTime_s = 0;
    NowTestAllTime_s = 0;
    NowDeviceNumString.append("测试标题");

    UpdateFirmwareFlag = 0;
}

MainWindow::~MainWindow()
{
    ChangeAppInfor();//结束之前将参数保存一下
    delete ui;
}

///////定时100ms调用一次/////////////
void MainWindow::Timer_100ms_Slot()
{
    if(DeviceRunStatus!=0)
    {
        static unsigned char PrevSec=0;
        QDateTime current_date_time = QDateTime::currentDateTime();
        unsigned char Sec = current_date_time.toString("ss").toInt();

        //更新定时器检测当前档位持续时间的显示
        if(PrevSec!=Sec)
        {
            PrevSec = Sec;
            NowStepTestTime_s ++;
            NowTestAllTime_s ++;
            QString TempStr = QString("%1:%2:%3").arg((unsigned char)(NowStepTestTime_s/3600)).arg((unsigned char)(NowStepTestTime_s%3600/60)).arg((unsigned char)(NowStepTestTime_s%60));
            ui->label_timerTestStepTime->setText(TempStr);
            QString TempStr2 = QString("%1:%2:%3").arg((unsigned char)(NowTestAllTime_s/3600)).arg((unsigned char)(NowTestAllTime_s%3600/60)).arg((unsigned char)(NowTestAllTime_s%60));
            ui->label_timerTestAllTime->setText(TempStr2);
            if((NowTestAllTime_s*10)>=(TimerConfig.objAllTime+TimerConfig.objAllTimeMaxMin))//本组定时器检测结束
            {
                ui->pushButton_stop->setText("开始检测");
                DeviceRunStatus = 0;
                DeviceTestStep = 1;
            }
            //每秒获取一次设备信息
            GetDeviceStatus(ShowThisDeviceStatus);
        }
        SendTestStep(0xff,DeviceTestStep);
    }
    else
    {
        //SendTestStep(0xff,0);//所有设备都要暂停

    }

    NotRecDataTimeCount ++;
    if(NotRecDataTimeCount>=5)//500ms没有收到数据了
    {
        if((UpdateFirmwareFlag)&&(myCom!=NULL)&&(myCom->isOpen()))//如果串口已经打开了，那么就发送升级"指令" ^_^
        {
            myCom->write("#",1);
        }
    }
}

/////////////存档配置文件操作///////////////////////
void MainWindow:: ChangeAppInfor()
{
    QVariantMap Json_VariantMap;
    Json_VariantMap.insert("version",QVariant(APPVERSION));
    Json_VariantMap.insert("configFileName",QVariant(ui->lineEdit_fileconfig->text()));
    Json_VariantMap.insert("COM",QVariant(ui->comboBox_com->currentIndex()));

    Json_VariantMap.insert("TestErrorNum",QVariant(TestErrorNum));
    Json_VariantMap.insert("TestAllTimeErrorNum",QVariant(TestAllTimeErrorNum));
    Json_VariantMap.insert("TestOkNum",QVariant(TestOkNum));
    QJsonDocument JsonDat = QJsonDocument::fromVariant(Json_VariantMap);
    QFile file("./app.json");
    if (file.open(QIODevice::WriteOnly | QIODevice::Text))
    {
        file.resize(0);//清空文件内容
        file.write(JsonDat.toJson(),JsonDat.toJson().size());
    }
    file.close();
}
char MainWindow:: OpenConfigFile(const QString &fileName)
{
    //检测文件内容是否为有效的配置
    QFile file(fileName);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        return false;
    }
    QByteArray FileData = file.readAll();
    QString jsonStr;
    jsonStr.append( FileData);
    QJsonDocument JsonDat = QJsonDocument::fromJson(jsonStr.toUtf8());
    if(JsonDat.object().value("version").toString().isEmpty())
    {
        return false;
    }
    ui->lineEdit_fileconfig->setText(fileName);
    ui->textEdit->append("open file name:"+fileName);
    ui->textEdit->append("参数更改日期："+JsonDat.object().value("date").toString());
    ui->textEdit->append("Version:"+JsonDat.object().value("version").toString());
    this->setWindowTitle(QString("精诚定时器检测台板-"+appVersion+"-")+fileName);

    unsigned char num;
    QDoubleSpinBox *tempDoubleSpinBox;
    QString objname;
    for(num=1;num<21;num ++)
    {
        //通道 接通时间
        objname.clear();
        objname.append(QString("doubleSpinBox_SetOnTime_%1").arg(num));
        tempDoubleSpinBox = this->findChild<QDoubleSpinBox *>(objname);
        tempDoubleSpinBox->setValue(JsonDat.object().value(objname).toString().toDouble());
        //通道 接通时间误差
        objname.clear();
        objname.append(QString("doubleSpinBox_SetOnTimeError_%1").arg(num));
        tempDoubleSpinBox = this->findChild<QDoubleSpinBox *>(objname);
        tempDoubleSpinBox->setValue(JsonDat.object().value(objname).toString().toDouble());
        //通道 断开时间
        objname.clear();
        objname.append(QString("doubleSpinBox_SetOffTime_%1").arg(num));
        tempDoubleSpinBox = this->findChild<QDoubleSpinBox *>(objname);
        tempDoubleSpinBox->setValue(JsonDat.object().value(objname).toString().toDouble());
        //通道 断开时间误差
        objname.clear();
        objname.append(QString("doubleSpinBox_SetOffTimeError_%1").arg(num));
        tempDoubleSpinBox = this->findChild<QDoubleSpinBox *>(objname);
        tempDoubleSpinBox->setValue(JsonDat.object().value(objname).toString().toDouble());
    }
    //总时间
    ui->doubleSpinBox_SetAllTime->setValue(JsonDat.object().value("doubleSpinBox_SetAllTime").toString().toDouble());
    //总时间误差
    ui->doubleSpinBox_SetAllTimeError->setValue(JsonDat.object().value("doubleSpinBox_SetAllTimeError").toString().toDouble());
    //定时器工作电压
    if(JsonDat.object().value("timerVolt").toString().toInt()==220)
    {
        ui->radioButton_30V->setChecked(false);
        ui->radioButton_220V->setChecked(true);
    }
    else
    {
        ui->radioButton_220V->setChecked(false);
        ui->radioButton_30V->setChecked(true);
    }
    //ChangeAppInfor();
    UpdateTimerConfigData();//更新到数据缓存区
    return true;
}

void MainWindow::UpdateTimerConfigData()
{
    unsigned char num;
    QDoubleSpinBox *tempDoubleSpinBox;
    QString objname;
    double tempf;
    unsigned short temp;
    for(num=1;num<21;num ++)
    {
        //通道 接通时间
        objname.clear();
        objname.append(QString("doubleSpinBox_SetOnTime_%1").arg(num));
        tempDoubleSpinBox = this->findChild<QDoubleSpinBox *>(objname);
        tempf = tempDoubleSpinBox->value()*10;
        temp = tempf;
        ((unsigned short*)TimerConfig.stepConfig)[4*num+0] = temp;
        //通道 接通时间误差
        objname.clear();
        objname.append(QString("doubleSpinBox_SetOnTimeError_%1").arg(num));
        tempDoubleSpinBox = this->findChild<QDoubleSpinBox *>(objname);
        tempf = tempDoubleSpinBox->value()*10;
        temp = tempf;
        ((unsigned short*)TimerConfig.stepConfig)[4*num+1] = temp;
        //通道 断开时间
        objname.clear();
        objname.append(QString("doubleSpinBox_SetOffTime_%1").arg(num));
        tempDoubleSpinBox = this->findChild<QDoubleSpinBox *>(objname);
        tempf = tempDoubleSpinBox->value()*10;
        temp = tempf;
        ((unsigned short*)TimerConfig.stepConfig)[4*num+2] = temp;
        //通道 断开时间误差
        objname.clear();
        objname.append(QString("doubleSpinBox_SetOffTimeError_%1").arg(num));
        tempDoubleSpinBox = this->findChild<QDoubleSpinBox *>(objname);
        tempf = tempDoubleSpinBox->value()*10;
        temp = tempf;
        ((unsigned short*)TimerConfig.stepConfig)[4*num+3] = temp;
    }
    //总时间
    TimerConfig.objAllTime = ui->doubleSpinBox_SetAllTime->value()*10;
    //总时间误差
    TimerConfig.objAllTimeMaxMin = ui->doubleSpinBox_SetAllTimeError->value()*10;
    //定时器工作电压
    if(ui->radioButton_30V->isChecked())
    {
        TimerConfig.objVolt = 30;
    }
    else
    {
        TimerConfig.objVolt = 220;
    }
}

void MainWindow::on_pushButton_openfile_clicked()
{
    QString filePath;
    if(ui->lineEdit_fileconfig->text().isEmpty())
    {
        filePath.append("./");
    }
    else
    {
        filePath.append(ui->lineEdit_fileconfig->text());
    }
    QString fileName = QFileDialog::getOpenFileName(\
                this,tr("open option file"),\
                filePath,tr("option files(*.json *.txt);;All files(*.*)"));
    if(fileName.isEmpty())
    {
        ui->textEdit->append("open failt");
        return;
    }
    else
    {
        OpenConfigFile(fileName);
    }
}
//存储当前配置
void MainWindow::on_pushButton_save_clicked()
{
    unsigned char num;
    QString filePath;
    if(ui->lineEdit_fileconfig->text().isEmpty())
    {
        filePath.append("./");
    }
    else
    {
        filePath.append(ui->lineEdit_fileconfig->text());
    }
    QString fileName = QFileDialog::getSaveFileName(this,
            tr("Open Config"),
            filePath,
            tr("Config Files (*.json)"));
    if (!fileName.isNull())
    {
        QDateTime current_date_time = QDateTime::currentDateTime();
        QString current_date = current_date_time.toString("yyyy-MM-dd hh:mm:ss ddd");

        QFile file(fileName);
        if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
        {
            QMessageBox::information(this,"错误信息","保存失败~~~~(>_<)~~~~");
            return;
        }

        QVariantMap Json_VariantMap;
        QString objname;
        QDoubleSpinBox *tempDoubleSpinBox;
        this->setWindowTitle(QString("精诚定时器检测台板-"+appVersion+"-")+fileName);
        ui->textEdit->append("file name:"+fileName);
        ui->lineEdit_fileconfig->setText(fileName);

        Json_VariantMap.insert("version",QVariant("V0.1"));
        Json_VariantMap.insert("date",QVariant(current_date));
        for(num=1;num<21;num ++)
        {
            //通道 接通时间
            objname.clear();
            objname.append(QString("doubleSpinBox_SetOnTime_%1").arg(num));
            tempDoubleSpinBox = this->findChild<QDoubleSpinBox *>(objname);
            Json_VariantMap.insert(objname,QVariant(tempDoubleSpinBox->text()));
            //通道 接通时间误差
            objname.clear();
            objname.append(QString("doubleSpinBox_SetOnTimeError_%1").arg(num));
            tempDoubleSpinBox = this->findChild<QDoubleSpinBox *>(objname);
            Json_VariantMap.insert(objname,QVariant(tempDoubleSpinBox->text()));
            //通道 断开时间
            objname.clear();
            objname.append(QString("doubleSpinBox_SetOffTime_%1").arg(num));
            tempDoubleSpinBox = this->findChild<QDoubleSpinBox *>(objname);
            Json_VariantMap.insert(objname,QVariant(tempDoubleSpinBox->text()));
            //通道 断开时间误差
            objname.clear();
            objname.append(QString("doubleSpinBox_SetOffTimeError_%1").arg(num));
            tempDoubleSpinBox = this->findChild<QDoubleSpinBox *>(objname);
            Json_VariantMap.insert(objname,QVariant(tempDoubleSpinBox->text()));
        }
        //总时间
        Json_VariantMap.insert("doubleSpinBox_SetAllTime",QVariant(ui->doubleSpinBox_SetAllTime->text()));
        //总时间误差
        Json_VariantMap.insert("doubleSpinBox_SetAllTimeError",QVariant(ui->doubleSpinBox_SetAllTimeError->text()));
        //定时器工作电压
        if(ui->radioButton_220V->isChecked())
        {
            Json_VariantMap.insert("timerVolt",QVariant("220"));
        }
        else
        {
            Json_VariantMap.insert("timerVolt",QVariant("30"));
        }
        QJsonDocument JsonDat = QJsonDocument::fromVariant(Json_VariantMap);
        ui->textEdit->append(JsonDat.object().value("date").toString());
        ui->textEdit->append("Version:"+JsonDat.object().value("version").toString());
        ui->textEdit->append("保存成功");
        file.resize(0);//清空文件内容
        file.write(JsonDat.toJson(),JsonDat.toJson().size());
        file.close();
        //ChangeAppInfor();
    }
    else
    {
        //点的是取消
        //ui->textEdit->append("not fileName");
    }
}

/////////////////////////串口//////////////////////////////////////
char MainWindow::OpenCom()
{
    if(myCom==NULL)
    {
        myCom = new QSerialPort(ui->comboBox_com->currentText());
        //ui->textEdit->append(ui->comboBox_com->currentText());
        if(myCom->open(QIODevice::ReadWrite))
        {
            myCom->setBaudRate(QSerialPort::Baud115200);
            myCom->setDataBits(QSerialPort::Data8);
            myCom->setStopBits(QSerialPort::OneStop);
            myCom->setFlowControl(QSerialPort::NoFlowControl);
            ui->textEdit->append("串口打开成功");
            ui->pushButton_openCOM->setText("关闭串口");
            //disconnect(myCom,SIGNAL(readyRead()),this,SLOT(readMyComSlot()));
            connect(myCom,SIGNAL(readyRead()),this,SLOT(readMyComSlot()));
            //ChangeAppInfor();//存储当前的串口号
        }
        else
        {
            ui->textEdit->append("串口打开失败");
            myCom->close();
            myCom->deleteLater();
            myCom = NULL;
        }
    }
    else
    {
        ui->pushButton_openCOM->setText("打开串口");
        myCom->close();
        myCom->deleteLater();
        myCom = NULL;
    }
    return 0;
}
//复位检测设备重新检测定时器，例如当前定时器检测好以后就复位一下等待下一次定时器插上
void MainWindow::SendTestReset(unsigned char dev)
{
    if((myCom!=NULL)&&(myCom->isOpen()))
    {
        //将用户配置的数据填充到发送数组中
        unsigned char tempSum=0;
        unsigned short step = 0;
        sentDatas[0] = 0xA5;
        sentDatas[1] = 0x5A;
        sentDatas[2] = 0x00;//本机为主机，所以地址为0x00
        tempSum = sentDatas[2];
        sentDatas[3] = RESETTEST;//更换定时器后重新检测
        tempSum += sentDatas[3];
        step = 4;
        sentDatas[step] = dev;//目标设备，如果是0xff那么就是所有设备
        tempSum += sentDatas[step];
        step ++;
        sentDatas[step] = RESETTEST;//更换定时器后重新检测
        tempSum += sentDatas[step];
        step ++;
        //校验和
        sentDatas[step] = tempSum;
        step ++;//本次发送的数据长度
        sentDatas[step] = 0x00;
        //发送
        myCom->write((const char*)sentDatas,step);
    }
}
void MainWindow::SendTestStep(unsigned char dev,unsigned char TestStep)//发送指令，控制设备检测步骤;dev是目标，0xff标示所有的板子都进行step档位的检测
{
    if((myCom!=NULL)&&(myCom->isOpen()))
    {
        //将用户配置的数据填充到发送数组中
        unsigned char tempSum=0;
        unsigned short step = 0;
        sentDatas[0] = 0xA5;
        sentDatas[1] = 0x5A;
        sentDatas[2] = 0x00;//本机为主机，所以地址为0x00
        tempSum = sentDatas[2];
        sentDatas[3] = SETSTEP;//后面发送的数据类型为：配置设备检测第几档
        tempSum += sentDatas[3];
        step = 4;
        sentDatas[step] = dev;//目标设备，如果是0xff那么就是所有设备
        tempSum += sentDatas[step];
        step ++;
        sentDatas[step] = TestStep;//配置测试第几档,为0的时候设备停止检测，处于暂停状态
        tempSum += sentDatas[step];
        step ++;
        //校验和
        sentDatas[step] = tempSum;
        step ++;//本次发送的数据长度
        sentDatas[step] = 0x00;
        //发送
        myCom->write((const char*)sentDatas,step);
    }
}
//获取对应设备的当前状态
void MainWindow::GetDeviceStatus(unsigned char dev)
{
    if((myCom!=NULL)&&(myCom->isOpen()))
    {
        //将用户配置的数据填充到发送数组中
        unsigned char tempSum=0;
        unsigned short step = 0;
        sentDatas[0] = 0xA5;
        sentDatas[1] = 0x5A;
        sentDatas[2] = 0x00;//本机为主机，所以地址为0x00
        tempSum = sentDatas[2];
        sentDatas[3] = READCOMM;//读取设备信息
        tempSum += sentDatas[3];
        step = 4;
        sentDatas[step] = dev;//目标设备，如果是0xff那么就是所有设备
        tempSum += sentDatas[step];
        step ++;
        sentDatas[step] = 0xff;//哪些信息
        tempSum += sentDatas[step];
        step ++;
        //校验和
        sentDatas[step] = tempSum;
        step ++;//本次发送的数据长度
        sentDatas[step] = 0x00;
        //发送
        myCom->write((const char*)sentDatas,step);
        GetDeviceStatusFlag = 1;
    }
}

void MainWindow::readMyComSlot()
{
    if(myCom!=NULL)
    {
        QByteArray tempBuff = myCom->readAll();
        QString tempStr = QString(tempBuff.toHex());
        //ui->textEdit->append(tempStr.toLatin1());
        RecBuffer.append(tempBuff);
        NotRecDataTimeCount = 0;//清零计时变量
        if(UpdateFirmwareFlag)
        {
            //"?&000&GetSize&end\r\n"
            //"?&001&GetApp&0000001&end\r\n"
            if(RecBuffer.lastIndexOf("\r\n")!=(-1))
            {
                QByteArray tempSendDat;
                int i=0;
                char temp = RecBuffer.indexOf("GetSize");
                tempSendDat.clear();
                ui->textEdit->append(RecBuffer);//显示接收到的数据
                if(temp != (-1))
                {
                    //serialPort.write("?Infor&"+datlist[1]+"&"+Appbuf.length+"&V"+AppVersion+"\r\n");//目标地址,APP长度，APP版本
                    tempSendDat.append("?Infor&");
                    tempSendDat.append((const char *)&RecBuffer.data()[RecBuffer.indexOf('?')+2],4);//"000&"
                    tempSendDat.append(QString("%1").arg(firmwareArray->length()));
                    tempSendDat.append("&V");
                    tempSendDat.append(FirmwareVersion);
                    tempSendDat.append("\r\n");
                    myCom->write(tempSendDat);
                    RecBuffer.clear();
                }
                else
                {
                    QByteArray tempFirmware;
                    int GetDataNum=0;
                    unsigned char sum;
                    tempFirmware.clear();
                    temp = RecBuffer.indexOf("GetApp");
                    if(temp != (-1))
                    {
                        tempFirmware.append( (const char *)&RecBuffer.data()[temp+7],7);
                        GetDataNum = tempFirmware.toInt();
                        tempFirmware.clear();
                        if(GetDataNum<=0)
                        {
                            RecBuffer.clear();
                            return;
                        }
                        if((GetDataNum*1024)<firmwareArray->length())
                        {
                            tempFirmware.append((const char *)&firmwareArray->data()[(GetDataNum-1)*1024],1024);
                        }
                        else
                        {
                            tempFirmware.append((const char *)&firmwareArray->data()[(GetDataNum-1)*1024],(firmwareArray->length()-((GetDataNum-1)*1024)));
                        }
                        sum = 0;
                        for(i=0;i<tempFirmware.length();i ++)
                        {
                            sum += tempFirmware.at(i);
                        }
                        //serialPort.write("?App&"+datlist[1]+"&"+getDataNum+"&"+sendbuf.length+"\r\n");//?App&000&1&1024&
                        //serialPort.write(sendbuf);
                        //serialPort.write(sumBuffer);
                        tempSendDat.append("?App&");
                        tempSendDat.append((const char *)&RecBuffer.data()[RecBuffer.indexOf('?')+2],4);//"000&"
                        tempSendDat.append(QString("%1&%2\r\n").arg(GetDataNum).arg(tempFirmware.length()));
                        tempSendDat.append(tempFirmware);
                        tempSendDat.append(sum);
                        //ui->textEdit->append(tempFirmware.toHex());
                        ui->textEdit->append(QString("CheckSum:%1").arg(sum));
                        myCom->write(tempSendDat);
                    }
                }
                RecBuffer.clear();
            }
            if(RecBuffer.length()>26)
            {
                RecBuffer.clear();
            }
        }
        else if(GetDeviceStatusFlag)//解析设备发回来的数据信息
        {
            if(RecBuffer.length()>32)
            {
                ui->textEdit->setText("AllTime:"+QString("%1").arg((unsigned short)(tempBuff.at(4)<<8)+tempBuff.at(5)));
                ui->textEdit->append("WeiboOn:"+QString("%1").arg((unsigned short)(tempBuff.at(6)<<8)+tempBuff.at(7)));
                ui->textEdit->append("WeiboOff:"+QString("%1").arg((unsigned short)(tempBuff.at(8)<<8)+tempBuff.at(9)));
                ui->textEdit->append("ShaokaoOn:"+QString("%1").arg((unsigned short)(tempBuff.at(10)<<8)+tempBuff.at(11)));
                ui->textEdit->append("ShaokaoOff:"+QString("%1").arg((unsigned short)(tempBuff.at(12)<<8)+tempBuff.at(13)));
                ui->textEdit->append("WeiboErrorFlag:"+QString("%1").arg((unsigned char)tempBuff.at(14)));//Weibo ErrorFlag
                ui->textEdit->append("Shaokao ErrorFlag:"+QString("%1").arg((unsigned char)tempBuff.at(15)));//Shaokao ErrorFlag

                ui->textEdit->append("ObjWeiboTimeOn:"+QString("%1").arg((unsigned short)(tempBuff.at(16)<<8)+tempBuff.at(17)));
                ui->textEdit->append("ObjWeiboTimeOnMaxMin:"+QString("%1").arg((unsigned short)(tempBuff.at(18)<<8)+tempBuff.at(19)));
                ui->textEdit->append("ObjWeiboTimeOff:"+QString("%1").arg((unsigned short)(tempBuff.at(20)<<8)+tempBuff.at(21)));
                ui->textEdit->append("ObjWeiboTimeOffMaxMin:"+QString("%1").arg((unsigned short)(tempBuff.at(22)<<8)+tempBuff.at(23)));

                ui->textEdit->append("ObjShaokaoTimeOn:"+QString("%1").arg((unsigned short)(tempBuff.at(24)<<8)+tempBuff.at(25)));
                ui->textEdit->append("ObjShaokaoTimeOnMaxMin:"+QString("%1").arg((unsigned short)(tempBuff.at(26)<<8)+tempBuff.at(27)));
                ui->textEdit->append("ObjShaokaoTimeOff:"+QString("%1").arg((unsigned short)(tempBuff.at(28)<<8)+tempBuff.at(29)));
                ui->textEdit->append("ObjShaokaoTimeOffMaxMin:"+QString("%1").arg((unsigned short)(tempBuff.at(30)<<8)+tempBuff.at(31)));

                RecBuffer.clear();
            }
            GetDeviceStatusFlag = 0;
        }
    }
}
void MainWindow::on_pushButton_openCOM_clicked()
{
    OpenCom();
}

void MainWindow::on_pushButton_sendConfig_clicked()
{
    if((myCom!=NULL)&&(myCom->isOpen()))
    {
        unsigned short temp;
        double tempf;
        if(DeviceRunStatus)//如果正在检测那么就提示用户停止检测
        {
            QMessageBox::information(this,"提醒","请先停止检测，再配置参数");
            return ;
        }
        //myCom->write("Hello QSerialPort!",sizeof("Hello QSerialPort!"));
        //将用户配置的数据填充到发送数组中
        QDoubleSpinBox *tempDoubleSpinBox;
        unsigned char num = 0,tempSum=0;
        unsigned short step = 0;
        QString objname;
        sentDatas[0] = 0xA5;
        sentDatas[1] = 0x5A;
        sentDatas[2] = 0x00;//本机为主机，所以地址为0x00
        tempSum = sentDatas[2];
        sentDatas[3] = WRITECOMM;//后面发送的数据类型
        tempSum += sentDatas[3];
        step = 4;
        for(num=1;num<21;num ++)
        {
            //这里先发送低字节，用来解决单片机那侧的大小端问题
            //通道 接通时间
            objname.clear();
            objname.append(QString("doubleSpinBox_SetOnTime_%1").arg(num));
            tempDoubleSpinBox = this->findChild<QDoubleSpinBox *>(objname);
            tempf = tempDoubleSpinBox->text().toDouble()*10;
            temp = tempf;
            sentDatas[step] = (temp&0x00ff);
            tempSum += sentDatas[step];
            step ++;
            sentDatas[step] = (temp)>>8;
            tempSum += sentDatas[step];
            step ++;
            //通道 接通时间误差
            objname.clear();
            objname.append(QString("doubleSpinBox_SetOnTimeError_%1").arg(num));
            tempDoubleSpinBox = this->findChild<QDoubleSpinBox *>(objname);
            tempf = tempDoubleSpinBox->text().toDouble()*10;
            temp = tempf;
            sentDatas[step] = (temp&0x00ff);
            tempSum += sentDatas[step];
            step ++;
            sentDatas[step] = (temp)>>8;
            tempSum += sentDatas[step];
            step ++;
            //通道 断开时间
            objname.clear();
            objname.append(QString("doubleSpinBox_SetOffTime_%1").arg(num));
            tempDoubleSpinBox = this->findChild<QDoubleSpinBox *>(objname);
            tempf = tempDoubleSpinBox->text().toDouble()*10;
            temp =tempf;
            sentDatas[step] = (temp&0x00ff);
            tempSum += sentDatas[step];
            step ++;
            sentDatas[step] = (temp)>>8;
            tempSum += sentDatas[step];
            step ++;
            //通道 断开时间误差
            objname.clear();
            objname.append(QString("doubleSpinBox_SetOffTimeError_%1").arg(num));
            tempDoubleSpinBox = this->findChild<QDoubleSpinBox *>(objname);
            tempf = tempDoubleSpinBox->text().toDouble()*10;
            temp = tempf;
            sentDatas[step] = (temp&0x00ff);
            tempSum += sentDatas[step];
            step ++;
            sentDatas[step] = (temp)>>8;
            tempSum += sentDatas[step];
            step ++;
        }
        //总时间
        tempf = ui->doubleSpinBox_SetAllTime->text().toDouble()*10;
        temp = tempf;
        sentDatas[step] = (temp)>>8;
        tempSum += sentDatas[step];
        step ++;
        sentDatas[step] = (temp&0x00ff);
        tempSum += sentDatas[step];
        step ++;
        //总时间误差
        tempf = ui->doubleSpinBox_SetAllTimeError->text().toDouble()*10;
        temp = tempf;
        sentDatas[step] = (temp)>>8;
        tempSum += sentDatas[step];
        step ++;
        sentDatas[step] = (temp&0x00ff);
        tempSum += sentDatas[step];
        step ++;
        //定时器工作电压
        //总时间
        if(ui->radioButton_220V->isChecked())
        {
            sentDatas[step] = 220;
        }
        else
        {
            sentDatas[step] = 30;
        }
        tempSum += sentDatas[step];
        step ++;
        //校验和
        sentDatas[step] = tempSum;
        step ++;
        //结束符
        sentDatas[step] = 0xC3;
        step ++;
        sentDatas[step] = 0x3C;
        step ++;//本次发送的数据长度
        //发送
        myCom->write((const char*)sentDatas,step);
        UpdateTimerConfigData();//更新到数据缓存区
    }
}
//////////////////////////////////////////////////////////////////

//根据控件的名字来找到控件，然后更改控件的显示内容
void MainWindow::SetDeviceButtonText()
{
    QPushButton *tempButton;
    unsigned char num = 0;
    QString objname;
    for(num=1;num<121;num ++)
    {
        objname.clear();
        objname.append(QString("pushButton_dev_%1").arg(num));
        tempButton = this->findChild<QPushButton *>(objname);
        tempButton->setText(QString("%1").arg(num));
        QObject::connect(tempButton,SIGNAL(clicked(bool)),this,SLOT(showDeviceDialog_Slot()));//绑定到处理函数
    }
}

//设置状态LED显示的颜色
void MainWindow::SetStatusLed(unsigned char index)
{
    QPixmap pixmap;
    switch(index)
    {
    case 0:
        pixmap.load(QString("./source/gray.png"));
    break;
    case 1:
        pixmap.load(QString("./source/green.png"));
    break;
    case 2:
        pixmap.load(QString("./source/orange.png"));
    break;
    case 3:
        pixmap.load(QString("./source/yellow.png"));
    break;
    case 4:
        pixmap.load(QString("./source/red.png"));
    break;
    }
    ui->label_status_led->setPixmap(pixmap);
}

//点击 重新检测 按键
void MainWindow::on_pushButton_ResetTest_clicked()
{
    if(DeviceRunStatus)
    {
        QMessageBox::information(this,"提醒","先暂停检测才能结束");
        return ;
    }
    NowStepTestTime_s = 0;//清零档位检测的时间
    NowTestAllTime_s = 0;//清零总时间
    DeviceRunStatus = 0;//暂停检测
    DeviceTestStep = 1;//准备从第一个档位开始检测
    ui->label_nowStep_value->setText("准备检测：一档");
    ui->pushButton_stop->setText("开始检测");
    SetStatusLed(LED_GRAY);
    SendTestReset(0xff);//所有
}
//开始或停止检测
void MainWindow::on_pushButton_stop_clicked()
{
    if((myCom!=NULL)&&(myCom->isOpen()))
    {
        if(DeviceRunStatus==0)
        {
            ui->pushButton_stop->setText("暂停检测");
            DeviceRunStatus = 1;//开始检测
            //失能选择检测步骤的按钮
//            ui->pushButton_startStep_1->setEnabled(false);
//            ui->pushButton_startStep_2->setEnabled(false);
//            ui->pushButton_startStep_3->setEnabled(false);
//            ui->pushButton_startStep_4->setEnabled(false);
//            ui->pushButton_startStep_5->setEnabled(false);
//            ui->pushButton_startStep_6->setEnabled(false);
//            ui->pushButton_startStep_7->setEnabled(false);
//            ui->pushButton_startStep_8->setEnabled(false);
//            ui->pushButton_startStep_9->setEnabled(false);
//            ui->pushButton_startStep_10->setEnabled(false);
            //
            switch(DeviceTestStep)
            {
            case 1:
                ui->label_nowStep_value->setText("正在检测：一档");
            break;
            case 2:
                ui->label_nowStep_value->setText("正在检测：二档");
            break;
            case 3:
                ui->label_nowStep_value->setText("正在检测：三档");
            break;
            case 4:
                ui->label_nowStep_value->setText("正在检测：四档");
            break;
            case 5:
                ui->label_nowStep_value->setText("正在检测：五档");
            break;
            case 6:
                ui->label_nowStep_value->setText("正在检测：六档");
            break;
            case 7:
                ui->label_nowStep_value->setText("正在检测：七档");
            break;
            case 8:
                ui->label_nowStep_value->setText("正在检测：八档");
            break;
            case 9:
                ui->label_nowStep_value->setText("正在检测：九档");
            break;
            case 10:
                ui->label_nowStep_value->setText("正在检测：十档");
            break;
            }
            SetStatusLed(LED_GREEN);
            //目前先同步检测,所有设备同时开始，同时结束
            SendTestStep(0xff,DeviceTestStep);
            SendTestStep(0xff,DeviceTestStep);
        }
        else
        {
            ui->pushButton_stop->setText("开始检测");
            DeviceRunStatus = 0;//暂停检测
            //失能选择检测步骤的按钮
//            ui->pushButton_startStep_1->setEnabled(true);
//            ui->pushButton_startStep_2->setEnabled(true);
//            ui->pushButton_startStep_3->setEnabled(true);
//            ui->pushButton_startStep_4->setEnabled(true);
//            ui->pushButton_startStep_5->setEnabled(true);
//            ui->pushButton_startStep_6->setEnabled(true);
//            ui->pushButton_startStep_7->setEnabled(true);
//            ui->pushButton_startStep_8->setEnabled(true);
//            ui->pushButton_startStep_9->setEnabled(true);
//            ui->pushButton_startStep_10->setEnabled(true);
            //
            switch(DeviceTestStep)
            {
            case 1:
                ui->label_nowStep_value->setText("暂停检测：一档");
            break;
            case 2:
                ui->label_nowStep_value->setText("暂停检测：二档");
            break;
            case 3:
                ui->label_nowStep_value->setText("暂停检测：三档");
            break;
            case 4:
                ui->label_nowStep_value->setText("暂停检测：四档");
            break;
            case 5:
                ui->label_nowStep_value->setText("暂停检测：五档");
            break;
            case 6:
                ui->label_nowStep_value->setText("暂停检测：六档");
            break;
            case 7:
                ui->label_nowStep_value->setText("暂停检测：七档");
            break;
            case 8:
                ui->label_nowStep_value->setText("暂停检测：八档");
            break;
            case 9:
                ui->label_nowStep_value->setText("暂停检测：九档");
            break;
            case 10:
                ui->label_nowStep_value->setText("暂停检测：十档");
            break;
            }
            SetStatusLed(LED_YELLOW);
            //目前先同步检测,所有设备同时开始，同时结束
            SendTestStep(0xff,0);//DeviceStep为0的时候设备暂停
            SendTestStep(0xff,0);//DeviceStep为0的时候设备暂停
        }
    }
    else
    {
        QMessageBox::information(this,"错误信息","请点击\"设置\"里面的\"打开串口\"~~~~(>_<)~~~~");
    }
}

void MainWindow::on_pushButton_startStep_1_clicked()
{
    if(DeviceTestStep!=1)
        NowStepTestTime_s = 0;//当前档位检测时间清零
    DeviceTestStep = 1;
    ui->label_nowStep_value->setText("检测：一档");
}

void MainWindow::on_pushButton_startStep_2_clicked()
{
    if(DeviceTestStep!=2)
        NowStepTestTime_s = 0;//当前档位检测时间清零
    DeviceTestStep = 2;
    ui->label_nowStep_value->setText("检测：二档");
}

void MainWindow::on_pushButton_startStep_3_clicked()
{
    if(DeviceTestStep!=3)
        NowStepTestTime_s = 0;//当前档位检测时间清零
    DeviceTestStep = 3;
    ui->label_nowStep_value->setText("检测：三档");
}

void MainWindow::on_pushButton_startStep_4_clicked()
{
    if(DeviceTestStep!=4)
        NowStepTestTime_s = 0;//当前档位检测时间清零
    DeviceTestStep = 4;
    ui->label_nowStep_value->setText("检测：四档");
}

void MainWindow::on_pushButton_startStep_5_clicked()
{
    if(DeviceTestStep!=5)
        NowStepTestTime_s = 0;//当前档位检测时间清零
    DeviceTestStep = 5;
    ui->label_nowStep_value->setText("检测：五档");
}

void MainWindow::on_pushButton_startStep_6_clicked()
{
    if(DeviceTestStep!=6)
        NowStepTestTime_s = 0;//当前档位检测时间清零
    DeviceTestStep = 6;
    ui->label_nowStep_value->setText("检测：六档");
}

void MainWindow::on_pushButton_startStep_7_clicked()
{
    if(DeviceTestStep!=7)
        NowStepTestTime_s = 0;//当前档位检测时间清零
    DeviceTestStep = 7;
    ui->label_nowStep_value->setText("检测：七档");
}

void MainWindow::on_pushButton_startStep_8_clicked()
{
    if(DeviceTestStep!=8)
        NowStepTestTime_s = 0;//当前档位检测时间清零
    DeviceTestStep = 8;
    ui->label_nowStep_value->setText("检测：八档");
}

void MainWindow::on_pushButton_startStep_9_clicked()
{
    if(DeviceTestStep!=9)
        NowStepTestTime_s = 0;//当前档位检测时间清零
    DeviceTestStep = 9;
    ui->label_nowStep_value->setText("检测：九档");
}

void MainWindow::on_pushButton_startStep_10_clicked()
{
    if(DeviceTestStep!=10)
        NowStepTestTime_s = 0;//当前档位检测时间清零
    DeviceTestStep = 10;
    ui->label_nowStep_value->setText("检测：十档");
}
/////////////////////////////////////////////////////////////////////////
//显示设备的状态和参数信息
void MainWindow::showDeviceDialog_Slot()
{
    QWidget *nowFocusWidget = this->focusWidget();//此时屏幕焦点的控件
    if(!nowFocusWidget)
        return;
    QPushButton *pb = qobject_cast<QPushButton*>(nowFocusWidget);
    NowDeviceNumString.clear();
    NowDeviceNumString.append(pb->text());
    Dialog *setdialog=new Dialog;
    Qt::WindowFlags flags = Qt::Dialog;
    setdialog->SetTitelStr(NowDeviceNumString);//标题显示当前设备的名称
    ShowThisDeviceStatus = pb->text().toInt();
    setdialog->SetDeviceNum(pb->text().toInt());//告诉设备信息窗口当前要显示的设备编号
    setdialog->setWindowFlags(flags);
    setdialog->setWindowModality(Qt::ApplicationModal); //阻塞除当前窗体之外的所有的窗体
    setdialog->show();
}


//清除累积故障数量
void MainWindow::on_pushButton_clearErrorNum_clicked()
{
    TestErrorNum = 0;
    ui->lcdNumber_errorNum->display(TestErrorNum);
    //ChangeAppInfor();
}
//清除累积完成数量
void MainWindow::on_pushButton_clearOkNum_clicked()
{
    TestOkNum = 0;
    ui->lcdNumber_okNum->display(TestOkNum);
    //ChangeAppInfor();
}
/////////////////////////////////////////////////////////////////////////////
//固件升级相关的
void MainWindow::on_pushButton_openbin_clicked()
{
    //QMessageBox mesg;
    QString fileName = QFileDialog::getOpenFileName(\
                this,tr("open Firmware file"),\
                "./",tr("Firmware files(*.bin);;All files(*.*)"));
    if(fileName.isEmpty())
    {
        //mesg.warning(this,"warning","open failt");
        ui->textEdit->append("open failt");
        return;
    }
    else
    {
        QFile file(fileName);
        ui->textEdit->append("Firmware file name:"+fileName);
        ui->lineEdit_filebin->setText(fileName);
        FirmwareVersion.clear();
        //FirmwareVersion.append((const char *)&fileName.toLatin1().data()[fileName.length()-6],2);
        FirmwareVersion.append("01");
        if (file.open(QIODevice::ReadOnly))
        {
            if(firmwareArray!=NULL)
            {
                delete firmwareArray;
            }
            firmwareArray = new QByteArray(file.readAll());
            ui->textEdit->append("Firmware size:"+QString("%1").arg(firmwareArray->length()));
            file.close();
        }
        //mesg.warning(this,"Ok","open file name:"+fileName);

    }
}

void MainWindow::on_pushButton_updatebin_clicked()//用户点击开始升级按键
{
    if(UpdateFirmwareFlag==0)
    {
        UpdateFirmwareFlag = 1;
        ui->pushButton_updatebin->setText("停止升级");
    }
    else
    {
        UpdateFirmwareFlag = 0;
        ui->pushButton_updatebin->setText("开始升级");
    }
}


